<template>
  <div class="relative w-full h-screen">
    <div class="flex h-screen bg-gradient-to-br from-gray-50 to-blue-50">
      <!-- 左侧控制面板 -->
      <div class="w-80 bg-white shadow-xl overflow-y-auto">
        <div class="p-6">
          <div class="section-card">
            <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
              <span class="mr-2">📝</span>
              文字设置
            </h3>
            <div class="space-y-4">
              <div>
                <label for="mainText" class="form-label">主标题</label>
                <input 
                  type="text" 
                  id="mainText" 
                  v-model="mainText"
                  placeholder="输入主标题"
                  class="form-input"
                >
              </div>
              
              <div>
                <label for="subText" class="form-label">副标题</label>
                <input 
                  type="text" 
                  id="subText" 
                  v-model="subText"
                  placeholder="输入副标题"
                  class="form-input"
                >
              </div>
              
              <div>
                <label for="fontSize" class="form-label">字体大小</label>
                <div class="flex items-center space-x-3">
                  <input 
                    type="range" 
                    id="fontSize" 
                    v-model="fontSize"
                    min="20" 
                    max="80"
                    class="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                  >
                  <span class="text-blue-600 font-medium min-w-[50px]">{{ fontSize }}px</span>
                </div>
              </div>
              
              <div>
                <label for="textColor" class="form-label">文字颜色</label>
                <input 
                  type="color" 
                  id="textColor" 
                  v-model="textColor"
                  class="w-16 h-10 border-none rounded-lg cursor-pointer"
                >
              </div>
            </div>
          </div>

          <div class="section-card">
            <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
              <span class="mr-2">🎨</span>
              背景设置
            </h3>
            <div class="space-y-4">
              <div>
                <label class="form-label">背景类型</label>
                <div class="flex space-x-4">
                  <label class="flex items-center cursor-pointer">
                    <input 
                      type="radio" 
                      name="bgType" 
                      value="solid" 
                      v-model="bgType"
                      class="mr-2 text-blue-600"
                    > 
                    <span class="text-gray-700">纯色</span>
                  </label>
                  <label class="flex items-center cursor-pointer">
                    <input 
                      type="radio" 
                      name="bgType" 
                      value="gradient" 
                      v-model="bgType"
                      class="mr-2 text-primary-600"
                    > 
                    <span class="text-gray-700">渐变</span>
                  </label>
                </div>
              </div>
              
              <div v-show="bgType === 'solid'">
                <label for="bgColor" class="form-label">背景颜色</label>
                <input 
                  type="color" 
                  id="bgColor" 
                  v-model="bgColor"
                  class="w-16 h-10 border-none rounded-lg cursor-pointer"
                >
              </div>
              
              <div v-show="bgType === 'gradient'" class="space-y-3">
                <div>
                  <label for="gradientColor1" class="form-label">渐变色 1</label>
                  <input 
                    type="color" 
                    id="gradientColor1" 
                    v-model="gradientColor1"
                    class="w-16 h-10 border-none rounded-lg cursor-pointer"
                  >
                </div>
                <div>
                  <label for="gradientColor2" class="form-label">渐变色 2</label>
                  <input 
                    type="color" 
                    id="gradientColor2" 
                    v-model="gradientColor2"
                    class="w-16 h-10 border-none rounded-lg cursor-pointer"
                  >
                </div>
              </div>
            </div>
          </div>

          <div class="section-card">
            <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
              <span class="mr-2">📐</span>
              尺寸设置
            </h3>
            <div class="space-y-4">
              <div>
                <label class="form-label">预设尺寸</label>
                <select 
                  v-model="presetSize" 
                  @change="handlePresetChange"
                  class="form-input"
                >
                  <option value="custom">自定义</option>
                  <option value="1920x1080">1920×1080 (16:9)</option>
                  <option value="1200x630">1200×630 (社交媒体)</option>
                  <option value="800x600">800×600 (4:3)</option>
                  <option value="1080x1080">1080×1080 (方形)</option>
                </select>
              </div>
              
              <div>
                <label for="canvasWidth" class="form-label">宽度</label>
                <input 
                  type="number" 
                  id="canvasWidth" 
                  v-model="canvasWidth"
                  min="100" 
                  max="3000"
                  class="form-input"
                >
              </div>
              
              <div>
                <label for="canvasHeight" class="form-label">高度</label>
                <input 
                  type="number" 
                  id="canvasHeight" 
                  v-model="canvasHeight"
                  min="100" 
                  max="3000"
                  class="form-input"
                >
              </div>
            </div>
          </div>

          <div class="section-card">
            <button @click="downloadCover" class="btn-primary w-full">
              <span class="mr-2">📥</span>
              下载封面图
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧预览区域 -->
      <div class="flex-1 flex items-center justify-center p-6">
        <div class="canvas-container">
          <canvas 
            ref="canvas"
            :width="canvasWidth" 
            :height="canvasHeight"
            @click="handleCanvasClick"
            @dblclick="handleCanvasDoubleClick"
            class="block max-w-full max-h-full cursor-pointer"
          ></canvas>
        </div>
      </div>
    </div>

    <!-- 动态输入框 -->
    <input
      v-if="editingText"
      ref="textInput"
      type="text"
      v-model="editingTextValue"
      :style="textInputStyle"
      @blur="finishTextEditing"
      @keydown="handleTextInputKeydown"
      class="absolute z-50 bg-white/90 border-2 border-blue-500 rounded px-3 py-2 text-center min-w-[200px] shadow-lg"
    >
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'

export default {
  name: 'CoverEditor',
  setup() {
    // 响应式数据
    const canvas = ref(null)
    const textInput = ref(null)
    const ctx = ref(null)
    
    // 文字设置
    const mainText = ref('我的封面')
    const subText = ref('副标题文字')
    const fontSize = ref(48)
    const textColor = ref('#ffffff')
    
    // 背景设置
    const bgType = ref('solid')
    const bgColor = ref('#667eea')
    const gradientColor1 = ref('#667eea')
    const gradientColor2 = ref('#764ba2')
    
    // 尺寸设置
    const presetSize = ref('1920x1080')
    const canvasWidth = ref(1920)
    const canvasHeight = ref(1080)
    
    // 编辑状态
    const editingText = ref(null)
    const editingTextValue = ref('')
    const textInputPosition = reactive({ x: 0, y: 0 })

    // 计算属性
    const textInputStyle = computed(() => {
      if (!editingText.value) return {}
      
      return {
        position: 'absolute',
        left: `${textInputPosition.x}px`,
        top: `${textInputPosition.y}px`,
        transform: 'translate(-50%, -50%)',
        background: 'rgba(255, 255, 255, 0.9)',
        border: '2px solid #667eea',
        borderRadius: '4px',
        padding: '8px 12px',
        fontSize: `${Math.max(16, fontSize.value * 0.3)}px`,
        fontWeight: editingText.value === 'main' ? 'bold' : 'normal',
        textAlign: 'center',
        color: textColor.value,
        minWidth: '200px',
        zIndex: '1000',
        boxShadow: '0 4px 12px rgba(0,0,0,0.2)'
      }
    })

    // 监听数据变化，重新渲染
    watch([mainText, subText, fontSize, textColor, bgType, bgColor, gradientColor1, gradientColor2], () => {
      render()
    })

    watch([canvasWidth, canvasHeight], () => {
      nextTick(() => {
        render()
      })
    })

    // 渲染函数
    const render = () => {
      if (!ctx.value) return

      // 清空画布
      ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)

      // 绘制背景
      if (bgType.value === 'solid') {
        ctx.value.fillStyle = bgColor.value
        ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
      } else {
        const gradient = ctx.value.createLinearGradient(0, 0, canvasWidth.value, canvasHeight.value)
        gradient.addColorStop(0, gradientColor1.value)
        gradient.addColorStop(1, gradientColor2.value)
        ctx.value.fillStyle = gradient
        ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
      }

      // 绘制文字
      const centerX = canvasWidth.value / 2
      const centerY = canvasHeight.value / 2

      // 主标题
      ctx.value.font = `bold ${fontSize.value}px Arial, sans-serif`
      ctx.value.fillStyle = textColor.value
      ctx.value.textAlign = 'center'
      ctx.value.textBaseline = 'middle'
      ctx.value.fillText(mainText.value, centerX, centerY - fontSize.value/3)

      // 副标题
      const subFontSize = Math.max(fontSize.value * 0.4, 16)
      ctx.value.font = `${subFontSize}px Arial, sans-serif`
      ctx.value.fillText(subText.value, centerX, centerY + fontSize.value/2)
    }

    // 预设尺寸处理
    const handlePresetChange = () => {
      if (presetSize.value === 'custom') return

      const [width, height] = presetSize.value.split('x').map(Number)
      canvasWidth.value = width
      canvasHeight.value = height
    }

    // 获取文字区域
    const getTextRegion = (x, y) => {
      const centerX = canvasWidth.value / 2
      const centerY = canvasHeight.value / 2

      // 检查主标题区域
      ctx.value.font = `bold ${fontSize.value}px Arial, sans-serif`
      const mainTextWidth = ctx.value.measureText(mainText.value).width
      const mainTextHeight = fontSize.value
      
      if (x >= centerX - mainTextWidth/2 && x <= centerX + mainTextWidth/2 &&
          y >= centerY - fontSize.value/3 - mainTextHeight/2 && 
          y <= centerY - fontSize.value/3 + mainTextHeight/2) {
        return 'main'
      }

      // 检查副标题区域
      const subFontSize = Math.max(fontSize.value * 0.4, 16)
      ctx.value.font = `${subFontSize}px Arial, sans-serif`
      const subTextWidth = ctx.value.measureText(subText.value).width
      const subTextHeight = subFontSize
      
      if (x >= centerX - subTextWidth/2 && x <= centerX + subTextWidth/2 &&
          y >= centerY + fontSize.value/2 - subTextHeight/2 && 
          y <= centerY + fontSize.value/2 + subTextHeight/2) {
        return 'sub'
      }

      return null
    }

    // 高亮文字
    const highlightText = (textType) => {
      render()
      
      const centerX = canvasWidth.value / 2
      const centerY = canvasHeight.value / 2

      // 绘制高亮边框
      ctx.value.strokeStyle = '#667eea'
      ctx.value.lineWidth = 2
      ctx.value.setLineDash([5, 5])

      if (textType === 'main') {
        ctx.value.font = `bold ${fontSize.value}px Arial, sans-serif`
        const textWidth = ctx.value.measureText(mainText.value).width
        const textHeight = fontSize.value
        ctx.value.strokeRect(
          centerX - textWidth/2 - 10,
          centerY - fontSize.value/3 - textHeight/2 - 5,
          textWidth + 20,
          textHeight + 10
        )
      } else if (textType === 'sub') {
        const subFontSize = Math.max(fontSize.value * 0.4, 16)
        ctx.value.font = `${subFontSize}px Arial, sans-serif`
        const textWidth = ctx.value.measureText(subText.value).width
        const textHeight = subFontSize
        ctx.value.strokeRect(
          centerX - textWidth/2 - 10,
          centerY + fontSize.value/2 - textHeight/2 - 5,
          textWidth + 20,
          textHeight + 10
        )
      }

      ctx.value.setLineDash([])
    }

    const handleCanvasClick = (e) => {
      if (editingText.value) return

      const rect = canvas.value.getBoundingClientRect()
      const scaleX = canvasWidth.value / rect.width
      const scaleY = canvasHeight.value / rect.height
      
      const x = (e.clientX - rect.left) * scaleX
      const y = (e.clientY - rect.top) * scaleY

      const textRegion = getTextRegion(x, y)
      if (textRegion) {
        highlightText(textRegion)
      }
    }

    const handleCanvasDoubleClick = (e) => {
      const rect = canvas.value.getBoundingClientRect()
      const scaleX = canvasWidth.value / rect.width
      const scaleY = canvasHeight.value / rect.height
      
      const x = (e.clientX - rect.left) * scaleX
      const y = (e.clientY - rect.top) * scaleY

      const textRegion = getTextRegion(x, y)
      if (textRegion) {
        startTextEditing(textRegion, e)
      }
    }

    const startTextEditing = (textType, e) => {
      if (editingText.value) finishTextEditing()

      editingText.value = textType
      const rect = canvas.value.getBoundingClientRect()
      
      textInputPosition.x = rect.left + rect.width/2
      textInputPosition.y = rect.top + rect.height/2

      // 设置初始值
      if (textType === 'main') {
        editingTextValue.value = mainText.value
      } else {
        editingTextValue.value = subText.value
      }

      nextTick(() => {
        textInput.value.focus()
        textInput.value.select()
      })
    }

    const finishTextEditing = () => {
      if (!editingText.value) return

      if (editingText.value === 'main') {
        mainText.value = editingTextValue.value
      } else if (editingText.value === 'sub') {
        subText.value = editingTextValue.value
      }

      editingText.value = null
      editingTextValue.value = ''
      render()
    }

    const handleTextInputKeydown = (e) => {
      if (e.key === 'Enter') {
        finishTextEditing()
      } else if (e.key === 'Escape') {
        editingText.value = null
        editingTextValue.value = ''
        render()
      }
    }

    const downloadCover = () => {
      const link = document.createElement('a')
      link.download = `封面图_${new Date().getTime()}.png`
      link.href = canvas.value.toDataURL('image/png')
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      showToast('封面图下载成功！')
    }

    const showToast = (message) => {
      const toast = document.createElement('div')
      toast.textContent = message
      toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #28a745;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        z-index: 1000;
        font-weight: 500;
      `
      
      document.body.appendChild(toast)
      
      setTimeout(() => {
        toast.style.opacity = '0'
        toast.style.transition = 'opacity 0.3s'
        setTimeout(() => {
          document.body.removeChild(toast)
        }, 300)
      }, 2000)
    }

    // 监听编辑值变化，实时更新
    watch(editingTextValue, () => {
      if (editingText.value === 'main') {
        mainText.value = editingTextValue.value
      } else if (editingText.value === 'sub') {
        subText.value = editingTextValue.value
      }
    })

    // 组件挂载
    onMounted(() => {
      ctx.value = canvas.value.getContext('2d')
      render()
    })

    return {
      // refs
      canvas,
      textInput,
      
      // 数据
      mainText,
      subText,
      fontSize,
      textColor,
      bgType,
      bgColor,
      gradientColor1,
      gradientColor2,
      presetSize,
      canvasWidth,
      canvasHeight,
      editingText,
      editingTextValue,
      
      // 计算属性
      textInputStyle,
      
      // 方法
      handlePresetChange,
      handleCanvasClick,
      handleCanvasDoubleClick,
      handleTextInputKeydown,
      finishTextEditing,
      downloadCover
    }
  }
}
</script>

 